
//------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using Apps.Models;
using Apps.Common;
using Microsoft.Practices.Unity;
using System.Transactions;
using Apps.BLL.Core;
using Apps.Locale;
using LinqToExcel;
using System.IO;
using System.Text;
using System.Linq.Expressions;
using Apps.IDAL.PUB;
using Apps.Models.PUB;
using Apps.IBLL.PUB;
using System.Text.RegularExpressions;

namespace Apps.BLL.PUB
{
	public partial class PUB_CARBLL: Virtual_PUB_CARBLL, IPUB_CARBLL
    {

    }
	public class Virtual_PUB_CARBLL
	{
        [Dependency]
        public IPUB_CARRepository m_Rep { get; set; }

        public virtual List<PUB_CAR> GetList(ref GridPager pager, string queryStr)
        {
            IQueryable<PUB_CAR> queryData = null;
            try
            {
                if (!string.IsNullOrWhiteSpace(queryStr))
                {
                    queryData = m_Rep.GetList(
                                    a => a.LPR.Contains(queryStr)
                                    || a.DRIVER_PHONE.Contains(queryStr)
                                    || a.POSTIONS.Contains(queryStr)
                                    );
                }
                else
                {
                    queryData = m_Rep.GetList();
                }
                pager.totalRows = queryData.Count();
                //排序
                queryData = LinqHelper.SortingAndPaging(queryData, pager.sort, pager.order, pager.page, pager.rows);
            }
            catch (Exception ex)
            { 
                throw ex;
            }
            return queryData.ToList();// CreateModelLists(ref queryData);
        }
		 
		public virtual List<PUB_CAR> GetPagerList(ref GridPager pager, Expression<Func<PUB_CAR, bool>> whereLambda )
        {

            IQueryable<PUB_CAR> queryData = m_Rep.GetList(whereLambda); 
             
            pager.totalRows = queryData.Count();
            //排序
            queryData = LinqHelper.SortingAndPaging(queryData, pager.sort, pager.order, pager.page, pager.rows);
            return queryData.ToList();//CreateModelLists(ref queryData);
        }
        public virtual List<PUB_CAR> GetList(Expression<Func<PUB_CAR, bool>> whereLambda)
        {

            IQueryable<PUB_CAR> queryData = m_Rep.GetList(whereLambda);

            return queryData.ToList();//CreateModelLists(ref queryData);
        }

        public virtual List<PUB_CARModel> GetLists(Expression<Func<PUB_CAR, bool>> whereLambda )
        {

            IQueryable<PUB_CAR> queryData = m_Rep.GetList(whereLambda); 
       
            return CreateModelList(ref queryData);
        }

		public virtual List<PUB_CAR> GetListByParentId(ref GridPager pager, string queryStr,object parentId)
        {
			return new List<PUB_CAR>();
		}

        public virtual List<PUB_CARModel> CreateModelList(ref IQueryable<PUB_CAR> queryData)
        {

            List<PUB_CARModel> modelList = (from r in queryData
                                              select new PUB_CARModel
                                              {
													CAR_ID = r.CAR_ID,
													RFID = r.RFID,
													LPR = r.LPR,
													DRIVER_IDCARD = r.DRIVER_IDCARD,
													DRIVER_PHONE = r.DRIVER_PHONE,
													SPECIFIED_WEIGHT = r.SPECIFIED_WEIGHT,
													TARE = r.TARE,
													TOTLE_LENGTH = r.TOTLE_LENGTH,
													TOTLE_WIDTH = r.TOTLE_WIDTH,
													LENGTH = r.LENGTH==null?0: (decimal)r.LENGTH,
													WIDTH = r.WIDTH == null ? 0 : (decimal)r.WIDTH,
													HEIGHT = r.HEIGHT == null ? 0 : (decimal)r.HEIGHT,
													POSTIONS = r.POSTIONS,
													REGISTER_USER_ID = r.REGISTER_USER_ID,
													REGISTER_TIME = r.REGISTER_TIME,
													UPDATE_USER_ID = r.UPDATE_USER_ID,
													UPDATE_TIME = r.UPDATE_TIME,
													STATUS = r.STATUS==null?0: (int)r.STATUS,
													UNREGISTER_TIME = r.UNREGISTER_TIME,
													UNREGISTER_REASON = r.UNREGISTER_REASON,
                                                    CAR_SIZE = r.CAR_SIZE,
          
                                              }).ToList();

            return modelList;
        }
        

        public virtual bool Create(ref ValidationErrors errors, PUB_CAR model)
        {
            try
            {
                PUB_CAR entity = m_Rep.GetById(model.CAR_ID);
                if (entity != null)
                {
                    errors.Add(Resource.PrimaryRepeat);
                    return false;
                }
                entity = new PUB_CAR();
               				entity.CAR_ID = model.CAR_ID;
				entity.RFID =string.IsNullOrEmpty(model.RFID)?"0": model.RFID;
				entity.LPR = model.LPR;
				entity.DRIVER_IDCARD = string.IsNullOrEmpty(model.DRIVER_IDCARD) ? "000000000000000000" : model.DRIVER_IDCARD;
                entity.DRIVER_PHONE = string.IsNullOrEmpty(model.DRIVER_PHONE) ? "00000000000" : model.DRIVER_PHONE;
                entity.SPECIFIED_WEIGHT = model.SPECIFIED_WEIGHT == null ? 0 : model.SPECIFIED_WEIGHT;
                entity.TARE =model.TARE==null ? 0 : model.TARE;
                entity.TOTLE_LENGTH = model.TOTLE_LENGTH== null ? 0 : model.TOTLE_LENGTH;
                entity.TOTLE_WIDTH = model.TOTLE_WIDTH==null ? 0 : model.TOTLE_WIDTH;
                entity.LENGTH = model.LENGTH;
				entity.WIDTH = model.WIDTH;
				entity.HEIGHT = model.HEIGHT;
				entity.POSTIONS = model.POSTIONS;
				entity.REGISTER_USER_ID = model.REGISTER_USER_ID;
				entity.REGISTER_TIME = model.REGISTER_TIME;
				entity.UPDATE_USER_ID = model.UPDATE_USER_ID;
				entity.UPDATE_TIME = model.UPDATE_TIME;
                entity.STATUS = model.STATUS==null ? 0 : (int)model.STATUS;
                entity.UNREGISTER_TIME = model.UNREGISTER_TIME;
				entity.UNREGISTER_REASON = model.UNREGISTER_REASON;
                entity.CAR_SIZE = model.CAR_SIZE;
  

                if (m_Rep.Create(entity))
                {
                    return true;
                }
                else
                {
                    errors.Add(Resource.InsertFail);
                    return false;
                }
            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }

		
		 public virtual bool Deletes(ref ValidationErrors errors,Expression<Func<PUB_CAR, bool>> whereLambda)
         {
		        try
				{
					using (DBContainer db = new DBContainer())
					{
				
							foreach (var entity in db.PUB_CAR.Where(whereLambda))
							{
								db.Entry(entity).State = System.Data.Entity.EntityState.Deleted;
							}

							if(db.SaveChanges()>0)
							{
								return true;
							}
							else
							{
								return false;
							}
			
					}
				}
				catch (Exception ex)
				{
					errors.Add(ex.Message);
					ExceptionHander.WriteException(ex);
					return false;
				}
        }

         public virtual bool Delete(ref ValidationErrors errors, object id)
        {
            try
            {
                if (m_Rep.Delete(id) == 1)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }

        public virtual bool Delete(ref ValidationErrors errors, object[] deleteCollection)
        {
            try
            {
                if (deleteCollection != null)
                {
                    using (TransactionScope transactionScope = new TransactionScope())
                    {
                        if (m_Rep.Delete(deleteCollection) == deleteCollection.Length)
                        {
                            transactionScope.Complete();
                            return true;
                        }
                        else
                        {
                            Transaction.Current.Rollback();
                            return false;
                        }
                    }
                }
                return false;
            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }

		
       

        public virtual bool Edit(ref ValidationErrors errors, PUB_CAR model)
        {
            try
            {
                PUB_CAR entity = m_Rep.GetById(model.CAR_ID);
                if (entity == null)
                {
                    errors.Add(Resource.Disable);
                    return false;
                }
                              				entity.CAR_ID = model.CAR_ID;
				entity.RFID = model.RFID;
				entity.LPR = model.LPR;
				//entity.DRIVER_IDCARD = model.DRIVER_IDCARD;
				//entity.DRIVER_PHONE = model.DRIVER_PHONE;
                entity.DRIVER_IDCARD = model.DRIVER_IDCARD=="0" ? "0" : model.DRIVER_IDCARD;
                entity.DRIVER_PHONE = model.DRIVER_PHONE =="0"? "0": model.DRIVER_PHONE;
                entity.SPECIFIED_WEIGHT = model.SPECIFIED_WEIGHT;
				entity.TARE = model.TARE;
				entity.TOTLE_LENGTH = model.TOTLE_LENGTH;
				entity.TOTLE_WIDTH = model.TOTLE_WIDTH;
				entity.LENGTH = model.LENGTH;
				entity.WIDTH = model.WIDTH;
				entity.HEIGHT = model.HEIGHT==0?(decimal?)null: model.HEIGHT;
				entity.POSTIONS = model.POSTIONS;
				entity.REGISTER_USER_ID = model.REGISTER_USER_ID;
				entity.REGISTER_TIME = model.REGISTER_TIME;
				entity.UPDATE_USER_ID = model.UPDATE_USER_ID;
				entity.UPDATE_TIME = model.UPDATE_TIME;
				entity.STATUS = model.STATUS==null?0: model.STATUS;
				entity.UNREGISTER_TIME = model.UNREGISTER_TIME;
				entity.UNREGISTER_REASON = model.UNREGISTER_REASON;
                entity.CAR_SIZE = model.CAR_SIZE;
 


                if (m_Rep.Edit(entity))
                {
                    return true;
                }
                else
                {
                    errors.Add(Resource.NoDataChange);
                    return false;
                }

            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }

      

        public virtual PUB_CAR GetById(object id)
        {
            if (IsExists(id))
            {
                PUB_CAR entity = m_Rep.GetById(id);
                PUB_CAR model = new PUB_CAR();
                              				model.CAR_ID = entity.CAR_ID;
				model.RFID = entity.RFID;
				model.LPR = entity.LPR;
				model.DRIVER_IDCARD = entity.DRIVER_IDCARD;
				model.DRIVER_PHONE = entity.DRIVER_PHONE;
				model.SPECIFIED_WEIGHT = entity.SPECIFIED_WEIGHT==null?0: entity.SPECIFIED_WEIGHT;
				model.TARE = entity.TARE == null ? 0 : entity.TARE;
                model.TOTLE_LENGTH = entity.TOTLE_LENGTH == null ? 0 : entity.TOTLE_LENGTH;
                model.TOTLE_WIDTH = entity.TOTLE_WIDTH == null ? 0 : entity.TOTLE_WIDTH;
                model.LENGTH = entity.LENGTH == null ? 0 : entity.LENGTH;
                model.WIDTH = entity.WIDTH == null ? 0 : entity.WIDTH;
                model.HEIGHT = entity.HEIGHT == null ? 0 : entity.HEIGHT;
                model.POSTIONS = entity.POSTIONS;
				model.REGISTER_USER_ID = entity.REGISTER_USER_ID;
				model.REGISTER_TIME = entity.REGISTER_TIME;
				model.UPDATE_USER_ID = entity.UPDATE_USER_ID;
				model.UPDATE_TIME = entity.UPDATE_TIME;
				model.STATUS = entity.STATUS == null ? 0 : entity.STATUS;
                model.UNREGISTER_TIME = entity.UNREGISTER_TIME;
				model.UNREGISTER_REASON = entity.UNREGISTER_REASON;
                model.CAR_SIZE = entity.CAR_SIZE;
 
                return model;
            }
            else
            {
                return null;
            }
        }

		public virtual PUB_CAR GetItem(Expression<Func<PUB_CAR, bool>> whereLambda)
        {
 
                PUB_CAR entity = m_Rep.GetItem(whereLambda);
                if (entity == null) return null;

                PUB_CAR model = new PUB_CAR();
                              				model.CAR_ID = entity.CAR_ID;
				model.RFID = entity.RFID;
				model.LPR = entity.LPR;
				model.DRIVER_IDCARD = entity.DRIVER_IDCARD;
				model.DRIVER_PHONE = entity.DRIVER_PHONE;
				model.SPECIFIED_WEIGHT = entity.SPECIFIED_WEIGHT;
				model.TARE = entity.TARE;
				model.TOTLE_LENGTH = entity.TOTLE_LENGTH;
				model.TOTLE_WIDTH = entity.TOTLE_WIDTH;
				model.LENGTH = (decimal)entity.LENGTH;
				model.WIDTH = (decimal)entity.WIDTH;
				model.HEIGHT = (decimal)entity.HEIGHT;
				model.POSTIONS = entity.POSTIONS;
				model.REGISTER_USER_ID = entity.REGISTER_USER_ID;
				model.REGISTER_TIME = entity.REGISTER_TIME;
				model.UPDATE_USER_ID = entity.UPDATE_USER_ID;
				model.UPDATE_TIME = entity.UPDATE_TIME;
				model.STATUS = entity.STATUS;
				model.UNREGISTER_TIME = entity.UNREGISTER_TIME;
				model.UNREGISTER_REASON = entity.UNREGISTER_REASON;
                model.CAR_SIZE = entity.CAR_SIZE;
 
                return model; 
        }


        /// <summary>
        /// 校验Excel数据,这个方法一般用于重写校验逻辑
        /// </summary>
        public virtual bool CheckImportData(string fileName, List<PUB_CAR> list, ref ValidationErrors errors)
        {

            var targetFile = new FileInfo(fileName);

            if (!targetFile.Exists)
            {

                errors.Add("导入的数据文件不存在");
                return false;
            }

            var excelFile = new ExcelQueryFactory(fileName);

            //对应列头
            excelFile.AddMapping<PUB_CAR>(x => x.LPR, "车牌号");
            excelFile.AddMapping<PUB_CAR>(x => x.DRIVER_IDCARD, "司机身份证");
            excelFile.AddMapping<PUB_CAR>(x => x.DRIVER_PHONE, "联系电话");
            excelFile.AddMapping<PUB_CAR>(x => x.SPECIFIED_WEIGHT, "额定载重");
            excelFile.AddMapping<PUB_CAR>(x => x.TARE, "皮重");
            excelFile.AddMapping<PUB_CAR>(x => x.TOTLE_LENGTH, "车辆长度(m)");
            excelFile.AddMapping<PUB_CAR>(x => x.TOTLE_WIDTH, "车辆宽度(m)");
            excelFile.AddMapping<PUB_CAR>(x => x.LENGTH, "车厢长度(m)");
            excelFile.AddMapping<PUB_CAR>(x => x.WIDTH, "车厢宽度(m)");
            excelFile.AddMapping<PUB_CAR>(x => x.HEIGHT, "车厢高度(m)");
            excelFile.AddMapping<PUB_CAR>(x => x.POSTIONS, "拉筋位置");

            //SheetName
            var excelContent = excelFile.Worksheet<PUB_CAR>(0);
            int rowIndex = 1;
            //检查数据正确性
            foreach (var row in excelContent)
            {
                var errorMessage = new StringBuilder();
                var entity = new PUB_CAR();
                entity.LPR = row.LPR;
                entity.DRIVER_IDCARD = row.DRIVER_IDCARD;
                entity.DRIVER_PHONE = row.DRIVER_PHONE;
                entity.SPECIFIED_WEIGHT = row.SPECIFIED_WEIGHT;
                entity.TARE = row.TARE;
                entity.TOTLE_LENGTH = row.TOTLE_LENGTH;
                entity.TOTLE_WIDTH = row.TOTLE_WIDTH;
                entity.LENGTH = row.LENGTH;
                entity.WIDTH = row.WIDTH;
                entity.HEIGHT = row.HEIGHT;
                entity.POSTIONS = Regex.Replace(String.Join(",", Regex.Replace(row.POSTIONS, @"([\u4e00-\u9fa5])", "-").Split('-').Where(a => !string.IsNullOrEmpty(a))), @"([\\s|\u3000|\uff0c]+)", ",");


                //=============================================================================
                if (errorMessage.Length > 0)
                {
                    errors.Add(string.Format(
                        "第 {0} 列发现错误：{1}{2}",
                        rowIndex,
                        errorMessage,
                        "<br/>"));
                }
                list.Add(entity);
                rowIndex += 1;
            }
            if (errors.Count > 0)
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// 保存数据
        /// </summary>
        public virtual void SaveImportData(IEnumerable<PUB_CAR> list)
        {
            try
            {
                using (DBContainer db = new DBContainer())
                {
                    foreach (var model in list)
                    {
                        PUB_CAR entity = new PUB_CAR();
                       	entity.CAR_ID = ResultHelper.NewId;
                        entity.RFID = string.IsNullOrEmpty(model.RFID) ? "0" : model.RFID;
						entity.LPR = model.LPR;
						entity.DRIVER_IDCARD = model.DRIVER_IDCARD;
						entity.DRIVER_PHONE = model.DRIVER_PHONE;
						entity.SPECIFIED_WEIGHT = model.SPECIFIED_WEIGHT;
						entity.TARE = model.TARE;
						entity.TOTLE_LENGTH = model.TOTLE_LENGTH;
						entity.TOTLE_WIDTH = model.TOTLE_WIDTH;
						entity.LENGTH = model.LENGTH;
						entity.WIDTH = model.WIDTH;
						entity.HEIGHT = model.HEIGHT;
						entity.POSTIONS = model.POSTIONS;
						entity.REGISTER_USER_ID = model.REGISTER_USER_ID;
						entity.REGISTER_TIME = DateTime.Now;
						entity.UPDATE_USER_ID = model.UPDATE_USER_ID;
						entity.UPDATE_TIME = model.UPDATE_TIME;
						entity.STATUS = model.STATUS;
						entity.UNREGISTER_TIME = model.UNREGISTER_TIME;
						entity.UNREGISTER_REASON = model.UNREGISTER_REASON;
                        entity.CAR_SIZE = model.CAR_SIZE;
 
                        db.PUB_CAR.Add(entity);
                    }
                    db.SaveChanges();
                }
            }
            catch
            {
                throw;
            }
        }


        public virtual bool IsExists(object id)
        {
            return m_Rep.IsExist(id);
        }
		  public void Dispose()
        { 
            
        }

	}
}
